package jccr;

import java.util.LinkedList;

public class TaskQueue implements DispatcherQueue {

	public TaskQueue( Dispatcher dispatcher ) {
		
		if ( dispatcher == null )
			throw new IllegalArgumentException();
	
		dispatcher.attach(this);
	}
	
	public void enqueue( Task task ) {

		synchronized( _tasks ) {
			_tasks.addLast(task);
		}
		
		notifyMonitor();
	}	
	
	public Task dequeue() {
		
		synchronized( _tasks ) {
						
			/* dequeue the task if available, otherwise return null */
			return _tasks.size() > 0 ? _tasks.removeFirst() : null;					
		}				
	}
	
	public int count() {
		
		synchronized( _tasks ) {
			return _tasks.size();
		}
	}
	
	public void monitor( DispatcherQueueMonitor monitor ) {
		
		_monitor  = monitor;		
	}
	
	 void notifyMonitor() {
		 
		 if ( _monitor != null )		 
			 _monitor.taskEnqueued(this);
	 }
	
	DispatcherQueueMonitor _monitor;
	LinkedList<Task> _tasks = new LinkedList<Task>();
}
